﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Security.Cryptography;
using System.Web.Security;
using System.Web;

namespace DataLevel
{
    public class UserDataAccess
    {
        static public int register(String email, String username, String pwd)
        {
            using (qingwen q = new qingwen())
            {
                Random r = new Random((int)DateTime.Now.AddDays(1).Ticks);
                String temp = null;
                for (int i = 0; i < 15; i++)
                {
                    temp += (char)(r.Next() % 26 + 'A');
                }
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

                account a = new account()
                {
                    Email = email,
                    nickname = username,
                    password = pwd,
                    random = temp,
                    valid_state = 0
                };
                userinfo b = new userinfo()
                {
                    userID = a.userID,
                    RP = 0,
                    register_time = DateTime.Now
                };
                try
                {
                    //新建账户
                    q.accounts.Add(a);
                    q.userinfoes.Add(b);
                    q.SaveChanges();
                    String mail = a.userID.ToString() + temp;
                    SmtpClient client = new SmtpClient();
                    client.Host = "smtp.163.com";
                    client.UseDefaultCredentials = true;
                    client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    client.Credentials = new System.Net.NetworkCredential("qingwenthu", "qiangpozheng");
                    MailMessage message = new MailMessage();
                    message.From = new MailAddress("qingwenthu@163.com", "清问问答系统");
                    message.To.Add(email);
                    String url = HttpContext.Current.Request.Url.Host;
                    url += ":" + HttpContext.Current.Request.ServerVariables.Get("SERVER_PORT");
                    message.Subject = "【清问】注册邮箱验证";
                    message.Body = "尊敬的用户您好： <p></p> 欢迎注册清问问答系统，请点击下面的链接以完成注册：<p></p> <a href=http://"
                        + url + "/validation.aspx?hash="
                        + BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(a.random)), 4, 8).ToLower().Replace("-", "")
                        + a.userID.ToString() + ">验证链接</a>";
                    message.SubjectEncoding = System.Text.Encoding.UTF8;
                    message.BodyEncoding = System.Text.Encoding.UTF8;
                    message.IsBodyHtml = true;
                    client.Send(message);

                    return 1;
                }
                catch (System.Exception ex)
                {
                    //建立账户失败
                    return 0;
                }
            }
        }

        static public int login(String email, String password)
        {
            using (qingwen q = new qingwen())
            {
                var p = from c in q.accounts
                        where c.Email == email && c.password == password
                        select c;
                if (p.Count<account>() == 0)
                    return 0;
                account s = p.ToList()[0];
                if (s.valid_state == 0)
                    return -1;
                return s.userID;
            }
        }

        static public int verify(int id, String verification)
        {
            using (qingwen q = new qingwen())
            {
                account p = q.accounts.FirstOrDefault(c => c.userID == id);
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                String ran = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(p.random)), 4, 8).ToLower().Replace("-", "");
                if (ran == verification)
                {
                    //已激活
                    if (p.valid_state == 1)
                        return -1;
                    p.valid_state = 1;
                    q.SaveChanges();
                    return 1;
                }
                return 0;
            }
        }

        static public account getUserAccount(int id){
            using (qingwen q = new qingwen())
            {
                var p = from c in q.accounts
                        where c.userID == id
                        select c;
                if (p.Count<account>() == 0)
                    return null;
                else
                    return p.ToList()[0];
            }
        }
        static public userinfo getUserInfo(int id)
        {
            using (qingwen q = new qingwen())
            {
                var p = from c in q.userinfoes
                        where c.userID == id
                        select c;
                if (p.Count<userinfo>() == 0)
                    return null;
                else
                    return p.ToList()[0];
            }
        }
        static public int setUserInfo(int id, string nickname, string major, short enteryear, string signature)
        {
            using (qingwen q = new qingwen())
            {
                try
                {
                    userinfo p = q.userinfoes.FirstOrDefault(c => c.userID == id);
                    p.major = major;
                    p.enteryear = enteryear;
                    p.signature = signature;
                    account s = q.accounts.FirstOrDefault(c => c.userID == id);
                    s.nickname = nickname;
                    q.SaveChanges();
                    return 1;
                }
                catch (Exception e)
                {
                    return -1;
                }
            }
        }
        static public int changePwd(int id, string oldpwd, string newpwd)
        {
            using (qingwen q = new qingwen())
            {
                var p = from c in q.accounts
                        where c.userID == id && c.password == oldpwd
                        select c;
                if (p.Count<account>() == 0)
                    return -1;
                account s = p.ToList()[0];
                s.password = newpwd;
                q.SaveChanges();
                return 1;

            }
        }
    }
}
